package com.flame.auth.server.controller;

import com.flame.auth.core.constants.AuthConstants;
import com.flame.auth.core.entity.TrustedPrincipal;
import com.flame.auth.server.controller.vo.LoginVo;
import com.flame.auth.server.service.AuthService;
import com.flame.core.protocol.Result;
import com.flame.core.utils.CipherUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * AuthController
 *
 * @author wuxintong
 * @since 2022/12/28
 */
@RestController
public class AuthController {

    @Autowired
    private AuthService authService;

    @PostMapping("/auth/login")
    public Result login(@Validated @RequestBody LoginVo loginVo, HttpServletRequest request,
                        HttpServletResponse response) {
        // 1、登录
        TrustedPrincipal trustedPrincipal = authService.login(loginVo, request);
        request.getSession().setAttribute(AuthConstants.TRUSTED_PRINCIPAL, trustedPrincipal);
        // 2、生成 token
        try {
            String token = CipherUtils
                    .sm4Encrypt(AuthConstants.SALT + trustedPrincipal.getAccount() + "_" + System.currentTimeMillis());
            response.addHeader(AuthConstants.TOKEN_HEADER, token);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.success(trustedPrincipal);
    }

    @PostMapping("/auth/logout")
    public Result logout(@Validated @RequestBody LoginVo loginVo, HttpSession session) {
        session.invalidate();
        return Result.success();
    }

}
